package com.github.nuggets.jwt;

import com.github.nuggets.constant.jwt.TokenEnhancerConstants;
import com.github.nuggets.entity.AuthenticAccount;
import com.github.nuggets.repository.AuthenticUserRepository;
import com.github.nuggets.service.AuthenticAccountDetailsService;
import com.github.nuggets.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;

/**
 * @description:
 * @author: wangsj
 * @date: 2022/3/18 10:57 上午
 */
@Service
public class JwtTokenEnhancer implements TokenEnhancer {

    @Autowired
    AuthenticUserRepository authenticUserRepository;

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {

        Authentication authentication = oAuth2Authentication.getUserAuthentication();
        String userName = authentication.getName();

        AuthenticAccount authenticAccount = authenticUserRepository.findByUsername(userName)
                .orElseThrow(() -> new UsernameNotFoundException("未找到该用户:" + userName));

        //jwt 内容增强
        HashMap<String, Object> additionalInfo = new HashMap<>();
        additionalInfo.put(TokenEnhancerConstants.ACCOUNT_ID,authenticAccount.getId());
        additionalInfo.put(TokenEnhancerConstants.ACCOUNT_USER_NAME,userName);
        additionalInfo.put(TokenEnhancerConstants.ACCOUNT_NICK_NAME,authenticAccount.getNickName());
        additionalInfo.put(TokenEnhancerConstants.ACCOUNT_ROLE,authenticAccount.getRole());
        additionalInfo.put(TokenEnhancerConstants.LOGIN_TIME, LocalDateTime.now().format(DateUtils.FORMATTER_YYYY_MM_DD_HH_MM_SS));
        ((DefaultOAuth2AccessToken) oAuth2AccessToken).setAdditionalInformation(additionalInfo);


        return oAuth2AccessToken;
    }
}
